import { createStore } from 'vuex'
import { getAllFactors, createFactor, updateFactor, deleteFactor } from '@/api/factor'
import { getAllStrategies, createStrategy, updateStrategy, deleteStrategy } from '@/api/strategy'
import { getAllPortfolios, createPortfolio, updatePortfolio, deletePortfolio } from '@/api/portfolio'
import { getAllTrades, createTrade, updateTrade, deleteTrade, updateTradeStatus } from '@/api/trade'
import user from './modules/user'

export default createStore({
  modules: {
    user
  },
  state: {
    // 全局状态
    user: {
      name: '管理员',
      avatar: '',
      role: 'admin'
    },
    // 基金列表
    funds: [],
    // 基金标签
    fundTags: [],
    // 因子列表
    factors: [],
    // 策略列表
    strategies: [],
    // 组合列表
    portfolios: [],
    // 交易列表
    trades: []
  },
  getters: {
    // 获取用户信息
    getUser: state => state.user,
    // 获取基金列表
    getFunds: state => state.funds,
    // 获取基金标签
    getFundTags: state => state.fundTags,
    // 获取因子列表
    getFactors: state => state.factors,
    // 获取策略列表
    getStrategies: state => state.strategies,
    // 获取组合列表
    getPortfolios: state => state.portfolios,
    // 获取交易列表
    getTrades: state => state.trades
  },
  mutations: {
    // 设置基金列表
    SET_FUNDS(state, funds) {
      state.funds = funds
    },
    // 添加基金
    ADD_FUND(state, fund) {
      state.funds.push(fund)
    },
    // 更新基金
    UPDATE_FUND(state, { index, fund }) {
      state.funds[index] = fund
    },
    // 删除基金
    DELETE_FUND(state, index) {
      state.funds.splice(index, 1)
    },
    
    // 设置基金标签
    SET_FUND_TAGS(state, tags) {
      state.fundTags = tags
    },
    // 添加基金标签
    ADD_FUND_TAG(state, tag) {
      state.fundTags.push(tag)
    },
    // 删除基金标签
    DELETE_FUND_TAG(state, index) {
      state.fundTags.splice(index, 1)
    },
    
    // 设置因子列表
    SET_FACTORS(state, factors) {
      state.factors = factors
    },
    // 添加因子
    ADD_FACTOR(state, factor) {
      state.factors.push(factor)
    },
    // 更新因子
    UPDATE_FACTOR(state, { index, factor }) {
      state.factors[index] = factor
    },
    // 删除因子
    DELETE_FACTOR(state, index) {
      state.factors.splice(index, 1)
    },
    
    // 设置策略列表
    SET_STRATEGIES(state, strategies) {
      state.strategies = strategies
    },
    // 添加策略
    ADD_STRATEGY(state, strategy) {
      state.strategies.push(strategy)
    },
    // 更新策略
    UPDATE_STRATEGY(state, { index, strategy }) {
      state.strategies[index] = strategy
    },
    // 删除策略
    DELETE_STRATEGY(state, index) {
      state.strategies.splice(index, 1)
    },
    
    // 设置组合列表
    SET_PORTFOLIOS(state, portfolios) {
      state.portfolios = portfolios
    },
    // 添加组合
    ADD_PORTFOLIO(state, portfolio) {
      state.portfolios.push(portfolio)
    },
    // 更新组合
    UPDATE_PORTFOLIO(state, { index, portfolio }) {
      state.portfolios[index] = portfolio
    },
    // 删除组合
    DELETE_PORTFOLIO(state, index) {
      state.portfolios.splice(index, 1)
    },
    
    // 设置交易列表
    SET_TRADES(state, trades) {
      state.trades = trades
    },
    // 添加交易
    ADD_TRADE(state, trade) {
      state.trades.push(trade)
    },
    // 更新交易
    UPDATE_TRADE(state, { index, trade }) {
      state.trades[index] = trade
    },
    // 删除交易
    DELETE_TRADE(state, index) {
      state.trades.splice(index, 1)
    }
  },
  actions: {
    // 加载基金数据
    loadFunds({ commit }) {
      // 模拟API请求
      const mockFunds = [
        { id: 1, code: '000001', name: '华夏成长混合', type: '混合型', tags: ['低风险', '稳健成长'], manager: '王经理', company: '华夏基金', nav: 1.2356, dailyReturn: 0.0023, yearReturn: 0.1245 },
        { id: 2, code: '000002', name: '嘉实增长混合', type: '混合型', tags: ['中风险', '价值投资'], manager: '李经理', company: '嘉实基金', nav: 2.3561, dailyReturn: -0.0011, yearReturn: 0.0935 },
        { id: 3, code: '000003', name: '易方达科技', type: '股票型', tags: ['高风险', '科技成长'], manager: '张经理', company: '易方达基金', nav: 3.1267, dailyReturn: 0.0127, yearReturn: 0.2541 }
      ]
      commit('SET_FUNDS', mockFunds)
    },
    
    // 加载基金标签
    loadFundTags({ commit }) {
      // 模拟API请求
      const mockTags = [
        { id: 1, name: '低风险', category: '风险' },
        { id: 2, name: '中风险', category: '风险' },
        { id: 3, name: '高风险', category: '风险' },
        { id: 4, name: '稳健成长', category: '风格' },
        { id: 5, name: '价值投资', category: '风格' },
        { id: 6, name: '科技成长', category: '风格' }
      ]
      commit('SET_FUND_TAGS', mockTags)
    },
    
    // 加载因子数据
    async loadFactors({ commit }) {
      try {
        // 尝试从API获取数据
        const response = await getAllFactors();
        if (response && Array.isArray(response)) {
          commit('SET_FACTORS', response);
          return;
        }
      } catch (error) {
        console.error('获取因子数据失败:', error);
        // 加载失败时使用模拟数据
        const mockFactors = [
          { id: 1, name: '市值因子', category: '基本面', description: '反映公司市值大小', formula: 'Market Cap = 股价 * 总股本' },
          { id: 2, name: 'PE因子', category: '估值', description: '反映公司估值水平', formula: 'PE = 股价 / 每股收益' },
          { id: 3, name: '动量因子', category: '技术', description: '反映股价趋势', formula: '过去12个月收益率' }
        ]
        commit('SET_FACTORS', mockFactors);
      }
    },
    
    // 添加因子
    async addFactor({ commit }, factor) {
      try {
        const response = await createFactor(factor);
        if (response) {
          // 使用后端返回的数据（包含ID）
          commit('ADD_FACTOR', response);
          return response;
        }
      } catch (error) {
        console.error('创建因子失败:', error);
        // 如果API失败，仍然在本地添加（但实际应用中应当提示错误）
        commit('ADD_FACTOR', factor);
        return factor;
      }
    },
    
    // 更新因子
    async updateFactor({ commit, state }, { id, factor }) {
      try {
        const response = await updateFactor(id, factor);
        if (response) {
          const index = state.factors.findIndex(f => f.id === id);
          if (index !== -1) {
            commit('UPDATE_FACTOR', { index, factor: response });
          }
          return response;
        }
      } catch (error) {
        console.error('更新因子失败:', error);
        // 如果API失败，仍然在本地更新
        const index = state.factors.findIndex(f => f.id === id);
        if (index !== -1) {
          commit('UPDATE_FACTOR', { index, factor });
        }
        return factor;
      }
    },
    
    // 删除因子
    async removeFactor({ commit, state }, id) {
      try {
        await deleteFactor(id);
        const index = state.factors.findIndex(f => f.id === id);
        if (index !== -1) {
          commit('DELETE_FACTOR', index);
        }
        return true;
      } catch (error) {
        console.error('删除因子失败:', error);
        // 即使API失败也尝试从本地删除
        const index = state.factors.findIndex(f => f.id === id);
        if (index !== -1) {
          commit('DELETE_FACTOR', index);
        }
        return false;
      }
    },
    
    // 加载策略数据
    async loadStrategies({ commit }) {
      try {
        // 从API获取数据
        const response = await getAllStrategies();
        if (response && Array.isArray(response)) {
          commit('SET_STRATEGIES', response);
          return;
        }
      } catch (error) {
        console.error('获取策略数据失败:', error);
        // 加载失败时使用模拟数据
        const mockStrategies = [
          { id: 1, name: '价值投资策略', description: '关注低估值、高股息的优质公司', factors: ['PE因子', '股息因子'], creator: '王分析师', createTime: '2023-05-15' },
          { id: 2, name: '成长投资策略', description: '关注高增长、高ROE的成长型公司', factors: ['ROE因子', '营收增长因子'], creator: '李分析师', createTime: '2023-06-20' },
          { id: 3, name: '量化多因子策略', description: '综合多种因子的量化选股策略', factors: ['市值因子', 'PE因子', '动量因子'], creator: '张分析师', createTime: '2023-07-10' }
        ];
        commit('SET_STRATEGIES', mockStrategies);
      }
    },
    
    // 添加策略
    async addStrategy({ commit }, strategy) {
      try {
        const response = await createStrategy(strategy);
        if (response) {
          // 使用后端返回的数据（包含ID）
          commit('ADD_STRATEGY', response);
          return response;
        }
      } catch (error) {
        console.error('创建策略失败:', error);
        // 如果API失败，仍然在本地添加
        const newStrategy = { ...strategy, id: Date.now() };
        commit('ADD_STRATEGY', newStrategy);
        return newStrategy;
      }
    },
    
    // 更新策略
    async updateStrategy({ commit, state }, { id, strategy }) {
      try {
        const response = await updateStrategy(id, strategy);
        if (response) {
          const index = state.strategies.findIndex(s => s.id === id);
          if (index !== -1) {
            commit('UPDATE_STRATEGY', { index, strategy: response });
          }
          return response;
        }
      } catch (error) {
        console.error('更新策略失败:', error);
        // 如果API失败，仍然在本地更新
        const index = state.strategies.findIndex(s => s.id === id);
        if (index !== -1) {
          commit('UPDATE_STRATEGY', { index, strategy });
        }
        return strategy;
      }
    },
    
    // 删除策略
    async removeStrategy({ commit, state }, id) {
      try {
        await deleteStrategy(id);
        const index = state.strategies.findIndex(s => s.id === id);
        if (index !== -1) {
          commit('DELETE_STRATEGY', index);
        }
        return true;
      } catch (error) {
        console.error('删除策略失败:', error);
        // 即使API失败也尝试从本地删除
        const index = state.strategies.findIndex(s => s.id === id);
        if (index !== -1) {
          commit('DELETE_STRATEGY', index);
        }
        return true;
      }
    },
    
    // 加载组合数据
    async loadPortfolios({ commit }) {
      try {
        // 从API获取数据
        const response = await getAllPortfolios();
        if (response && Array.isArray(response)) {
          commit('SET_PORTFOLIOS', response);
          return;
        }
      } catch (error) {
        console.error('获取组合数据失败:', error);
        // 加载失败时使用模拟数据
        const mockPortfolios = [
          { id: 1, name: '稳健增长组合', strategy: '价值投资策略', funds: ['华夏成长混合', '嘉实增长混合'], weights: [0.6, 0.4], creator: '王经理', createTime: '2023-08-01', performance: 0.0856 },
          { id: 2, name: '高成长组合', strategy: '成长投资策略', funds: ['易方达科技', '嘉实增长混合'], weights: [0.7, 0.3], creator: '李经理', createTime: '2023-08-15', performance: 0.1245 },
          { id: 3, name: '均衡配置组合', strategy: '量化多因子策略', funds: ['华夏成长混合', '易方达科技', '嘉实增长混合'], weights: [0.4, 0.3, 0.3], creator: '张经理', createTime: '2023-09-01', performance: 0.0723 }
        ];
        commit('SET_PORTFOLIOS', mockPortfolios);
      }
    },
    
    // 添加组合
    async addPortfolio({ commit }, portfolio) {
      try {
        const response = await createPortfolio(portfolio);
        if (response) {
          // 使用后端返回的数据（包含ID）
          commit('ADD_PORTFOLIO', response);
          return response;
        }
      } catch (error) {
        console.error('创建组合失败:', error);
        // 如果API失败，仍然在本地添加
        const newPortfolio = { ...portfolio, id: Date.now() };
        commit('ADD_PORTFOLIO', newPortfolio);
        return newPortfolio;
      }
    },
    
    // 更新组合
    async updatePortfolio({ commit, state }, { id, portfolio }) {
      try {
        const response = await updatePortfolio(id, portfolio);
        if (response) {
          const index = state.portfolios.findIndex(p => p.id === id);
          if (index !== -1) {
            commit('UPDATE_PORTFOLIO', { index, portfolio: response });
          }
          return response;
        }
      } catch (error) {
        console.error('更新组合失败:', error);
        // 如果API失败，仍然在本地更新
        const index = state.portfolios.findIndex(p => p.id === id);
        if (index !== -1) {
          commit('UPDATE_PORTFOLIO', { index, portfolio });
        }
        return portfolio;
      }
    },
    
    // 删除组合
    async removePortfolio({ commit, state }, id) {
      try {
        await deletePortfolio(id);
        const index = state.portfolios.findIndex(p => p.id === id);
        if (index !== -1) {
          commit('DELETE_PORTFOLIO', index);
        }
        return true;
      } catch (error) {
        console.error('删除组合失败:', error);
        // 即使API失败也尝试从本地删除
        const index = state.portfolios.findIndex(p => p.id === id);
        if (index !== -1) {
          commit('DELETE_PORTFOLIO', index);
        }
        return true;
      }
    },
    
    // 加载交易数据
    async loadTrades({ commit }) {
      try {
        // 从API获取数据
        const response = await getAllTrades();
        if (response && Array.isArray(response)) {
          commit('SET_TRADES', response);
          return;
        }
      } catch (error) {
        console.error('获取交易数据失败:', error);
        // 加载失败时使用模拟数据
        const mockTrades = [
          { id: 1, portfolio: '稳健增长组合', action: '买入', fund: '华夏成长混合', amount: 100000, price: 1.2356, date: '2023-08-05', status: '已完成' },
          { id: 2, portfolio: '高成长组合', action: '买入', fund: '易方达科技', amount: 150000, price: 3.1267, date: '2023-08-20', status: '已完成' },
          { id: 3, portfolio: '均衡配置组合', action: '买入', fund: '嘉实增长混合', amount: 80000, price: 2.3561, date: '2023-09-05', status: '处理中' },
          { id: 4, portfolio: '稳健增长组合', action: '卖出', fund: '嘉实增长混合', amount: 30000, price: 2.4125, date: '2023-09-10', status: '已完成' },
          { id: 5, portfolio: '高成长组合', action: '调仓', fund: '易方达科技', amount: 50000, price: 3.2541, date: '2023-09-15', status: '处理中' }
        ];
        commit('SET_TRADES', mockTrades);
      }
    },
    
    // 添加交易
    async addTrade({ commit }, trade) {
      try {
        const response = await createTrade(trade);
        if (response) {
          // 使用后端返回的数据（包含ID）
          commit('ADD_TRADE', response);
          return response;
        }
      } catch (error) {
        console.error('创建交易失败:', error);
        // 如果API失败，仍然在本地添加
        const newTrade = { ...trade, id: Date.now() };
        commit('ADD_TRADE', newTrade);
        return newTrade;
      }
    },
    
    // 更新交易
    async updateTrade({ commit, state }, { id, trade }) {
      try {
        const response = await updateTrade(id, trade);
        if (response) {
          const index = state.trades.findIndex(t => t.id === id);
          if (index !== -1) {
            commit('UPDATE_TRADE', { index, trade: response });
          }
          return response;
        }
      } catch (error) {
        console.error('更新交易失败:', error);
        // 如果API失败，仍然在本地更新
        const index = state.trades.findIndex(t => t.id === id);
        if (index !== -1) {
          commit('UPDATE_TRADE', { index, trade });
        }
        return trade;
      }
    },
    
    // 更新交易状态
    async updateTradeStatus({ commit, state }, { id, status }) {
      try {
        const response = await updateTradeStatus(id, status);
        if (response) {
          const index = state.trades.findIndex(t => t.id === id);
          if (index !== -1) {
            const updatedTrade = { ...state.trades[index], status };
            commit('UPDATE_TRADE', { index, trade: updatedTrade });
          }
          return response;
        }
      } catch (error) {
        console.error('更新交易状态失败:', error);
        // 如果API失败，仍然在本地更新
        const index = state.trades.findIndex(t => t.id === id);
        if (index !== -1) {
          const updatedTrade = { ...state.trades[index], status };
          commit('UPDATE_TRADE', { index, trade: updatedTrade });
        }
        return { id, status };
      }
    },
    
    // 删除交易
    async removeTrade({ commit, state }, id) {
      try {
        await deleteTrade(id);
        const index = state.trades.findIndex(t => t.id === id);
        if (index !== -1) {
          commit('DELETE_TRADE', index);
        }
        return true;
      } catch (error) {
        console.error('删除交易失败:', error);
        // 即使API失败也尝试从本地删除
        const index = state.trades.findIndex(t => t.id === id);
        if (index !== -1) {
          commit('DELETE_TRADE', index);
        }
        return true;
      }
    }
  }
}) 